package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.Role;
import cn.wolfcode.wms.mapper.RoleMapper;
import cn.wolfcode.wms.page.PageResult;
import cn.wolfcode.wms.query.QueryObject;
import cn.wolfcode.wms.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper mapper;

    public void save(Role role, Long[] permissionIds, Long[] menuIds) {
        mapper.insert(role);
        if (permissionIds != null) {
            for (Long permissionId : permissionIds) {
                mapper.saveRelationByRoleId(role.getId(), permissionId);
            }
        }
        if (menuIds != null) {
            for (Long menuId : menuIds) {
                mapper.saveMenuRelation(role.getId(), menuId);
            }
        }
    }

    public void delete(long id) {
        mapper.deleteByPrimaryKey(id);
        mapper.deleteRelationByRoleId(id);
        mapper.deleteMenuRelation(id);
    }

    public void update(Role role, Long[] permissionIds, Long[] menuIds) {
        mapper.updateByPrimaryKey(role);
        mapper.deleteRelationByRoleId(role.getId());
        mapper.deleteMenuRelation(role.getId());
        if (permissionIds != null) {
            for (Long permissionId : permissionIds) {
                mapper.saveRelationByRoleId(role.getId(), permissionId);
            }
        }
        if (menuIds != null) {
            for (Long menuId : menuIds) {
                mapper.saveMenuRelation(role.getId(), menuId);
            }
        }
    }

    public Role get(long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<Role> list() {
        return mapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int rows = mapper.queryForCount(qo);
        if (rows == 0) {
            return PageResult.empty(qo.getPageSize());
        }
        List<?> result = mapper.queryForList(qo);
        return new PageResult(result, rows, qo.getCurrentPage(), qo.getPageSize());
    }
}
